<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>在线支付</p>
    </header>

    <!-- 订单信息部分 -->
    <h3>订单信息：</h3>
    <div class="order-info">
      <p>
        {{ order.business?.businessName || businessNameFallback }}
        <i class="fa fa-caret-down" @click="toggleDetail"></i>
      </p>
      <p>&#165;{{ formatPrice(calculatedTotal) }}</p>
    </div>

    <!-- 订单明细部分 -->
    <ul class="order-detailet" v-show="showDetails">
      <li v-for="item in orderItems" :key="item.id">
        <p>{{ item.food?.foodName || '商品' }} x {{ item.quantity }}</p>
        <p>&#165;{{ formatPrice((item.food?.foodPrice || 0) * item.quantity) }}</p>
      </li>
      <li>
        <p>配送费</p>
        <p>&#165;{{ formatPrice(deliveryPrice) }}</p>
      </li>
      <li class="order-total">
        <p>总计</p>
        <p>&#165;{{ formatPrice(calculatedTotal) }}</p>
      </li>
    </ul>

    <!-- 支付方式部分 -->
    <div class="payment-section">
      <h3>选择支付方式：</h3>
      <ul class="payment-types">
        <li
            v-for="payment in paymentMethods"
            :key="payment.type"
            :class="{ active: selectedPayment === payment.type }"
            @click="selectPayment(payment.type)"
        >
          <i v-if="payment.balance" :class="'fa ' + payment.icon" class="payment-icon"></i>
          <img v-else :src="payment.icon" :alt="payment.name" />
          <div class="payment-info">
            <span>{{ payment.name }}</span>
            <span v-if="payment.balance" class="balance-text">
              余额：¥{{ formatPrice(walletBalance) }}
            </span>
          </div>
          <i class="fa fa-check-circle" v-if="selectedPayment === payment.type"></i>
        </li>
      </ul>

      <!-- 透支选项提示 -->
      <div v-if="showOverdraftOption" class="overdraft-prompt">
        <div class="prompt-header">
          <i class="fas fa-exclamation-circle"></i>
          <span>余额不足，可选择透支支付</span>
        </div>
        <div class="prompt-info">
          <p>当前余额：¥{{ formatPrice(walletBalance) }}</p>
          <p>支付金额：¥{{ formatPrice(calculatedTotal) }}</p>
          <p>透支金额：¥{{ formatPrice(calculatedTotal - walletBalance) }}</p>
        </div>
        <label class="overdraft-checkbox">
          <input type="checkbox" v-model="allowOverdraft" />
          <span>我已知晓并同意使用透支服务</span>
        </label>
        <div class="overdraft-rules">
          <i class="fas fa-info-circle"></i>
          <small>透支规则：按日计息，30天内免息，逾期将影响信用</small>
        </div>
      </div>
    </div>

    <div class="payment-button">
      <button @click="payOrder" :disabled="paying || !order.id">
        {{ paying ? '支付中...' : '确认支付' }}
      </button>
    </div>

    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import Footer from "../components/Footer.vue";
import { orderAPI } from '@/api/order.js';
import { walletAPI } from '@/api/wallet.js';

const route = useRoute();
const router = useRouter();

const orderId = ref(route.query.orderId);
const order = ref({
  id: null,
  business: {},
  orderTotal: 0
});
const orderItems = ref([]);
const showDetails = ref(false);
const paying = ref(false);
const selectedPayment = ref('wallet');
const businessNameFallback = ref('商家信息加载中...');

// 钱包余额
const walletBalance = ref(0);
const walletLoading = ref(false);

// 透支选项
const allowOverdraft = ref(false);

// 支付方式配置
const paymentMethods = ref([
  {
    type: 'wallet',
    name: '钱包支付',
    icon: 'fa-wallet',
    balance: true
  },
  {
    type: 'alipay',
    name: '支付宝',
    icon: require('@/assets/alipay.png'),
    balance: false
  },
  {
    type: 'wechat',
    name: '微信支付',
    icon: require('@/assets/wechat.png'),
    balance: false
  }
]);

// 计算属性
const deliveryPrice = computed(() => {
  return order.value.business?.deliveryPrice || 0;
});

// 显示透支选项（仅当选择钱包支付且余额不足时）
const showOverdraftOption = computed(() => {
  return selectedPayment.value === 'wallet' &&
         walletBalance.value < calculatedTotal.value;
});

const calculatedTotal = computed(() => {
  // 如果orderTotal有值则使用，否则计算商品总价+配送费
  if (order.value.orderTotal > 0) {
    return order.value.orderTotal;
  }

  const itemsTotal = orderItems.value.reduce((sum, item) => {
    return sum + (item.food?.foodPrice || 0) * item.quantity;
  }, 0);

  return itemsTotal + deliveryPrice.value;
});

// 获取订单详情 - 修复数据处理逻辑
const fetchOrderDetails = async () => {
  if (!orderId.value) {
    console.error('订单ID为空');
    alert('订单信息错误');
    router.push('/orderList');
    return;
  }

  try {
    console.log('正在获取订单详情，订单ID:', orderId.value);
    const response = await orderAPI.getOrderById(orderId.value);
    console.log('订单详情响应:', response);

    if (!response || !response.data) {
      throw new Error('未获取到订单数据');
    }

    let orderData = response.data;

    // 处理不同的响应格式
    if (response.data.success !== undefined) {
      // 如果包含success字段
      if (response.data.success) {
        orderData = response.data.data || response.data;
      } else {
        throw new Error(response.data.message || '获取订单信息失败');
      }
    }

    // 确保orderData是对象
    if (typeof orderData === 'object' && orderData !== null) {
      // 深度解析订单数据
      parseOrderData(orderData);
    } else {
      throw new Error('订单数据格式错误');
    }
  } catch (error) {
    console.error("获取订单详情失败:", error);
    businessNameFallback.value = '商家信息加载失败';
    alert('获取订单信息失败: ' + (error.message || '请重试'));
  }
};

// 深度解析订单数据
const parseOrderData = (orderData) => {
  console.log('原始订单数据:', orderData);

  // 尝试多种可能的数据结构
  let businessInfo = {};
  let items = [];
  let total = 0;
  // console.log(orderData[0].food.business)
  // 尝试获取商家信息
  if (orderData[0].food.business) {
    businessInfo = orderData[0].food.business;
  } else if (orderData.businessId) {
    businessInfo = { id: orderData.businessId };
  }
  // console.log(businessInfo)
  // 尝试获取订单项
  if (orderData.list && Array.isArray(orderData.list)) {
    items = orderData.list;
  } else if (orderData.orderItems && Array.isArray(orderData.orderItems)) {
    items = orderData.orderItems;
  } else if (Array.isArray(orderData)) {
    items = orderData;
  }

  // 尝试获取总金额
  if (orderData.orderTotal) {
    total = parseFloat(orderData.orderTotal);
  } else if (orderData.total) {
    total = parseFloat(orderData.total);
  }

  // 更新订单信息
  order.value = {
    id: orderData.id || orderData.orderId || orderId.value,
    orderTotal: total,
    business: businessInfo
  };

  orderItems.value = items;

  console.log('解析后的订单数据:', order.value);
  console.log('解析后的订单项:', orderItems.value);
  console.log('商家信息:', businessInfo);
};

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined) return '0.00';
  const num = parseFloat(price);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

// 显示/隐藏详情
const toggleDetail = () => {
  showDetails.value = !showDetails.value;
};

// 选择支付方式
const selectPayment = (paymentType) => {
  selectedPayment.value = paymentType;
  // 如果切换到钱包支付且余额不足，默认不选择透支
  if (paymentType === 'wallet' && walletBalance.value < calculatedTotal.value) {
    allowOverdraft.value = false;
  }
};

// 处理浏览器后退按钮
const handlePopState = () => {
  router.push({ path: "/orderList" });
};

// 获取当前用户ID
const getCurrentUserId = () => {
  try {
    // 从sessionStorage中获取userId（登录后存储的键名）
    const userId = sessionStorage.getItem('userId');
    return userId ? parseInt(userId) : null;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
};

// 获取钱包余额
const fetchWalletBalance = async () => {
  const userId = getCurrentUserId();
  if (!userId) return;

  walletLoading.value = true;
  try {
    const response = await walletAPI.getBalance(userId);
    if (response.data && response.data.success) {
      walletBalance.value = response.data.data.availableBalance || 0;
    } else if (response.data && response.data.availableBalance !== undefined) {
      walletBalance.value = response.data.availableBalance || 0;
    }
  } catch (error) {
    console.error('获取钱包余额失败:', error);
    walletBalance.value = 0;
  } finally {
    walletLoading.value = false;
  }
};

// 支付订单
const payOrder = async () => {
  if (!order.value.id) {
    alert('订单信息不完整，无法支付');
    return;
  }

  paying.value = true;

  try {
    let success = false;

    if (selectedPayment.value === 'wallet') {
      // 使用钱包支付
      const userId = getCurrentUserId();
      if (!userId) {
        alert('请先登录');
        router.push('/login');
        return;
      }

      // 获取商家用户ID（从订单中获取）
      const businessUserId = order.value.business?.businessOwner?.id;
      if (!businessUserId) {
        alert('商家信息不完整，无法支付');
        paying.value = false;
        return;
      }

      // 检查余额
      if (walletBalance.value < calculatedTotal.value) {
        // 余额不足，检查是否允许透支
        if (!allowOverdraft.value) {
          alert(`钱包余额不足！\n当前余额：¥${formatPrice(walletBalance.value)}\n需要支付：¥${formatPrice(calculatedTotal.value)}\n\n如需使用透支支付，请勾选"我已知晓并同意使用透支服务"`);
          paying.value = false;
          return;
        }
      }

      // 调用钱包支付API（包含allowOverdraft参数）
      const paymentResponse = await walletAPI.payment({
        payerId: userId,
        receiverId: businessUserId,
        amount: calculatedTotal.value,
        orderId: order.value.id,
        allowOverdraft: allowOverdraft.value
      });

      if (paymentResponse.data && paymentResponse.data.success !== false) {
        // 钱包支付成功，更新订单状态为已支付
        const updateResponse = await orderAPI.updateOrderState(order.value.id, 1);
        if (updateResponse.data) {
          success = true;
        }
      } else {
        alert('钱包支付失败：' + (paymentResponse.data.message || '请重试'));
        paying.value = false;
        return;
      }
    } else {
      // 使用第三方支付（支付宝、微信）
      const response = await orderAPI.updateOrderState(order.value.id, 1);

      if (response.data) {
        if (response.data.success === true) {
          success = true;
        } else if (response.data > 0) {
          success = true;
        } else if (response.data === true) {
          success = true;
        }
      }
    }

    if (success) {
      alert("支付成功！");
      router.push({ path: "/orderList" });
    } else {
      alert("支付失败！");
    }
  } catch (error) {
    console.error("支付请求失败:", error);
    const errorMsg = error.response?.data?.message || error.message || '请重试';
    alert("支付请求失败：" + errorMsg);
  } finally {
    paying.value = false;
  }
};

onMounted(() => {
  console.log('Payment页面加载，订单ID:', orderId.value);
  fetchOrderDetails();
  fetchWalletBalance();

  // 添加历史记录和监听事件
  history.pushState(null, null, document.URL);
  window.addEventListener("popstate", handlePopState);
});

onUnmounted(() => {
  window.removeEventListener("popstate", handlePopState);
});
</script>

<style scoped>
/* 样式保持不变 */
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 订单信息部分 ******************/
.wrapper h3 {
  margin-top: 12vw;
  box-sizing: border-box;
  padding: 4vw 4vw 0;
  font-size: 4vw;
  font-weight: 300;
  color: #999;
}

.wrapper .order-info {
  box-sizing: border-box;
  padding: 4vw;
  font-size: 4vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.wrapper .order-info p:first-child {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.wrapper .order-info p:last-child {
  color: orangered;
  font-weight: bold;
  font-size: 4.5vw;
}

.wrapper .order-info .fa-caret-down {
  cursor: pointer;
  color: #999;
  font-size: 5vw;
}

/****************** 订单明细部分 ******************/
.wrapper .order-detailet {
  width: 100%;
  background-color: #f9f9f9;
  padding: 2vw 0;
}

.wrapper .order-detailet li {
  width: 100%;
  box-sizing: border-box;
  padding: 1.5vw 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 3.5vw;
  color: #666;
}

.wrapper .order-detailet li.order-total {
  border-top: 1px dashed #ddd;
  font-weight: bold;
  color: #333;
  margin-top: 1vw;
  padding-top: 2vw;
  font-size: 4vw;
}

/****************** 支付方式部分 ******************/
.wrapper .payment-section {
  margin-top: 3vw;
}

.wrapper .payment-section h3 {
  padding: 4vw 4vw 2vw;
  margin: 0;
  font-size: 4vw;
  font-weight: 300;
  color: #999;
}

.wrapper .payment-types {
  width: 100%;
  background: white;
}

.wrapper .payment-types li {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.wrapper .payment-types li:last-child {
  border-bottom: none;
}

.wrapper .payment-types li:hover {
  background-color: #f9f9f9;
}

.wrapper .payment-types li.active {
  background-color: #f0f8ff;
}

.wrapper .payment-types li img,
.wrapper .payment-types li .payment-icon {
  width: 8vw;
  height: 8vw;
  margin-right: 3vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wrapper .payment-types li .payment-icon {
  font-size: 6vw;
  color: #0097ff;
}

.wrapper .payment-types li .payment-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1vw;
}

.wrapper .payment-types li .payment-info span:first-child {
  font-size: 4vw;
  color: #333;
}

.wrapper .payment-types li .balance-text {
  font-size: 3vw;
  color: #999;
}

.wrapper .payment-types li .fa-check-circle {
  font-size: 5vw;
  color: #38ca73;
}

/* 透支选项提示样式 */
.overdraft-prompt {
  margin-top: 3vw;
  padding: 4vw;
  background: linear-gradient(135deg, #fff7e6 0%, #ffe6cc 100%);
  border-radius: 2vw;
  border-left: 1vw solid #ff9800;
}

.prompt-header {
  display: flex;
  align-items: center;
  gap: 2vw;
  margin-bottom: 3vw;
  font-size: 4vw;
  font-weight: bold;
  color: #ff6b00;
}

.prompt-header i {
  font-size: 5vw;
}

.prompt-info {
  background: white;
  padding: 3vw;
  border-radius: 1vw;
  margin-bottom: 3vw;
}

.prompt-info p {
  margin: 1.5vw 0;
  font-size: 3.5vw;
  color: #666;
  display: flex;
  justify-content: space-between;
}

.prompt-info p:first-child {
  margin-top: 0;
}

.prompt-info p:last-child {
  margin-bottom: 0;
  font-weight: bold;
  color: #ff6b00;
}

.overdraft-checkbox {
  display: flex;
  align-items: center;
  gap: 2vw;
  padding: 2vw;
  background: #f0f8ff;
  border-radius: 1vw;
  cursor: pointer;
  margin-bottom: 2vw;
}

.overdraft-checkbox input[type="checkbox"] {
  width: 4vw;
  height: 4vw;
  cursor: pointer;
}

.overdraft-checkbox span {
  font-size: 3.5vw;
  color: #333;
  font-weight: 500;
}

.overdraft-rules {
  display: flex;
  align-items: center;
  gap: 1.5vw;
  padding: 2vw 3vw;
  background: #e3f2fd;
  border-radius: 1vw;
}

.overdraft-rules i {
  font-size: 3.5vw;
  color: #1976d2;
}

.overdraft-rules small {
  font-size: 3vw;
  color: #666;
  line-height: 1.5;
}

.wrapper .payment-button {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw;
  margin-top: 3vw;
}

.wrapper .payment-button button {
  width: 100%;
  height: 10vw;
  border: none;
  outline: none;
  border-radius: 4px;
  background-color: #38ca73;
  color: #fff;
  font-size: 4.2vw;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s;
}

.wrapper .payment-button button:hover:not(:disabled) {
  background-color: #2fb863;
}

.wrapper .payment-button button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>